<?php 
require_once ("DB.php");
require_once ("ENCRYPT.php");
date_default_timezone_set('Asia/Chongqing');
function session_getCurrentUser() {
    session_start();
    $serial = $_SESSION['user.serial'];
    if ($serial) {
        $user = user_getByField('serial', $serial);
    }
    return $user;
}
function session_getCurrentClient() {
    session_start();
    $user_IP = ($_SERVER["HTTP_VIA"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : $_SERVER["REMOTE_ADDR"];
    $user_IP = ($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];
    $value = $_COOKIE['USS'];
    $mTime = microtime();
    $time = time();
    if (!$value) {
        $value = ENCRYPT::en($user_IP.'|'.$mTime, ENCRYPT_KEY);
        setcookie("USS", $value, $time + 60 * 60 * 24 * 365, "/");
    }
    $client = array("ip"=>$user_IP,
             "uss"=>$value,
             "mTime"=>$mTime,
             "time"=>$time,
             "timeFormat"=>date("Y-m-d H:i:s", $time),
             "session"=>$_COOKIE['PHPSESSID']);
    return $client;
}
/**
 * session_setCurrentUser
 *
 * 添加当前用户到session
 *
 * @param int $serial 对应用户的$serial
 */
function session_setCurrentUser($serial) {
    session_start();
    $_SESSION['user.serial'] = $serial;
}
/**
 * session_unsetCurrentUser
 *
 * 释放对应session
 */
function session_unsetCurrentUser() {
    session_start();
    unset($_SESSION['user.serial']);
}
/**
 * 获得用户信息
 * @param string $name 对应列名
 * @param string $value 所对应的名称
 * @return array 返回查询结果
 */
function user_getByField($name, $value) {
    if (!isset($value)) {
        return null;
    } elseif (!is_array($value)) {
        $whereSyntax = "where $name=?";
        $conn = getDBConnection();
        $result = $conn->query("select serial, id, email, nickname, register_time, last_access_time, before_last_access_time, image from t_user $whereSyntax",
             array($value));
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set = $row;
        }
        $result->free();
        $conn->disconnect();
        return $set;
    } elseif (count($value) == 0) {
        return array();
    } else {
        $values = $value;
        $whereSyntax = "where $name in (";
        foreach ($values as $value) {
            $whereSyntax .= "?, ";
        }
        $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
        $whereSyntax .= ")";
        $conn = getDBConnection();
        $result = $conn->query("select serial, id, email, nickname, register_time, last_access_time, before_last_access_time, image from t_user $whereSyntax",
             $values);
        $set = array();
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set[$row[$name]] = $row;
        }
        $result->free();
        $conn->disconnect();
        return $set;
    }
}
/**
 * user_getXByField
 *
 * 获得用户基本信息
 *
 * @param string $name 对应用户的$serial
 * @param string $value 对应用户名称
 * @return array 返回用户基本信息
 */
function user_getXByField($name, $value) {
    if (!isset($value)) {
        return null;
    } elseif (!is_array($value)) {
        $whereSyntax = "where $name=?";
        
        $conn = getDBConnection();
        $result = $conn->query("select * from t_user $whereSyntax", array($value));
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set = $row;
        }
        $result->free();
        $conn->disconnect();
        
        return $set;
    } elseif (count($value) == 0) {
        return array();
    } else {
        $values = $value;
        $whereSyntax = "where $name in (";
        foreach ($values as $value) {
            $whereSyntax .= "?, ";
        }
        $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
        $whereSyntax .= ")";
        $conn = getDBConnection();
        $result = $conn->query("select serial, id, email, nickname, register_time, last_access_time, before_last_access_time, image from t_user $whereSyntax",
             $values);
        $set = array();
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set[$row[$name]] = $row;
        }
        $result->free();
        $conn->disconnect();
        return $set;
    }
}
/**
 * 获取用户个人资料
 * @param int $user_serial 对应用户的$serial
 *
 * @return array 返回用户资料信息
 */
function user_getProfiles($user_serial) {
    if ((int) $user_serial <= 0) {
        return null;
    }
    $profiles = array();
    $conn = getDBConnection();
    $result = $conn->query("select user_serial, profile_key, profile_value from t_user_profile where user_serial=?",
         array($user_serial));
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $profiles[$row['profile_key']] = $row['profile_value'];
    }
    $result->free();
    $conn->disconnect();
    return $profiles;
}
/**
 * user_auth
 *
 * 判断登陆信息
 *
 * @param int $serial 对应用户的$serial
 * @param atring $password 对应的密码
 * @return bool 返回判断结果
 */
function user_auth($serial, $password) {
    $conn = getDBConnection();
    $result = $conn->query("select serial from t_user where serial=? and password=?", array($serial, $password));
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row;
    }
    $result->free();
    $conn->disconnect();
    if ($set) {
        return true;
    } else {
        return false;
    }
}
/**
 * user_create
 *
 * 创建用户
 *
 * @param array $user 存储用户信息所用的数组
 *
 * @return int 返回最后添加的$serial
 */
function user_create($user) {
    $conn = getDBConnection();
    $conn->query("insert into t_user(id, email, nickname, password, description, register_time) value(?, ?, ?, ?, ?, ?)",
         array($user['id'], $user['email'], $user['nickname'], $user['password'], $user['description'], date('Y-m-d H:i:s',
         time())));
    $result = $conn->query("select last_insert_id()");
    if ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row;
    }
    $result->free();
    $conn->disconnect();
    $serial = $set['last_insert_id()'];
    if ($serial) {
        $defaultRole = role_getByField('id', role_getDefault());
        role_grant($serial, $defaultRole['serial']);
    }
    return $serial;
}
/**
 * user_profile_create
 *
 * 建立用户个人资料
 *
 * @param int $user_serial 对应用户$serial
 * @param array $profile 对应资料内容
 *
 * @return bool 返回结果
 */
function user_profile_create($user_serial, $profile) {
    $conn = getDBConnection();
    if (count($profile)) {
        foreach ($profile as $profile_key=>$profile_value) {
            $conn->query("insert into t_user_profile (user_serial, profile_key, profile_value) values (?, ?, ?)",
                 array($user_serial, $profile_key, $profile_value));
        }
    }
    return true;
}
/**
 * user_deleteByField
 *
 * 后台删除用户信息
 *
 * @param string $name 所要删除信息的列名称
 * @param int $value 所要删除信息对应的用户$serial
 */
function user_deleteByField($name, $value) {
    //grant
    $user = user_getByField($name, $value);
    if (!is_array($value)) {
        if ($user) {
            $users = array($value=>$user);
        } else {
            $user = array();
        }
    } else {
        $users = $user;
    }
    $userSerials = array();
    foreach ($users as $user) {
        $userSerials[] = $user['serial'];
    }
    role_grant($userSerials, null);
    //delete
    if (!isset($value)) {
    } elseif (!is_array($value)) {
        $whereSyntax = "where $name=?";
        $conn = getDBConnection();
        $conn->query("delete from t_user $whereSyntax", array($value));
        $conn->disconnect();
    } elseif (count($value) == 0) {
    } else {
        $values = $value;
        $whereSyntax = "where $name in (";
        foreach ($values as $value) {
            $whereSyntax .= "?, ";
        }
        $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
        $whereSyntax .= ")";
        $conn = getDBConnection();
        $conn->query("delete from t_user $whereSyntax", $values);
        $conn->disconnect();
    }
    if (!isset($values)) {
        return;
    }
    if (is_array($values) && count($values) == 0) {
        return;
    }
}
/**
 * user_update
 *
 * 修改用户信息
 *
 * @param array $user 存储用户信息所用的数组
 */
function user_update($user) {
    $conn = getDBConnection();
    $updateValue = array();
    $serial = $user['serial'];
    unset($user['serial']);
    foreach ($user as $field=>$value) {
        $updateFieldSyntax .= "$field=?, ";
        $updateValue[$field] = $value;
    }
    $updateValue['serial'] = $serial;
    $updateFieldSyntax = substr($updateFieldSyntax, 0, strlen($updateFieldSyntax) - 2);
    $conn->query("update t_user set $updateFieldSyntax where serial=?", $updateValue);
    $conn->disconnect();
}
/**
 * user_getCount
 *
 * 查询用户个数
 *
 * @return int 返回个数
 */
function user_getCount() {
    $conn = getDBConnection();
    $result = $conn->query("select count(serial) from t_user");
    $set = 0;
    if ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row['count(serial)'];
    }
    $result->free();
    $conn->disconnect();
    return $set;
}

/**
 * user_getAll
 *
 * 查询用户信息
 *
 * @param int $start 开始查询位置
 * @param int $size 每页条数
 * @param string $orderBy 排序方法
 * @return array 返回结果
 */
function user_getAll($start, $size, $orderBy) {
    $conn = getDBConnection();
    $result = $conn->query("select t_user.serial as serial, t_user.id as id, t_user.image as image, email, nickname, register_time, last_access_time, before_last_access_time, t_role.serial as role_serial, t_role.id as role_id, t_role.name as role_name from t_user left join t_mapping_user_role on t_mapping_user_role.user_serial = t_user.serial left join t_role on t_role.serial = t_mapping_user_role.role_serial order by t_user.$orderBy");
    $set = array();
    $i = 0;
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        if ($i >= $start) {
            if ($size != - 1 && count($set) >= $size) {
                break;
            }
            $set[] = $row;
        }
        $i++;
    }
    $result->free();
    $conn->disconnect();
    return $set;
}
/**
 * user_getCountSearchByFacet
 *
 * 返回搜索结果数量
 *
 * @param string $facet 要搜索的列名称
 * @param string $keyword 要搜索的内容
 *
 * @return int 返回数量值
 */
function user_getCountSearchByFacet($facet, $keyword) {
    if (in_array($facet, array('id', 'email', 'nickname'))) {
        $whereSyntax = " where t_user.$facet like '%$keyword%' ";
    } elseif ($facet == 'city') {
        $whereSyntax = " where t_user_profile.profile_key='city' and t_user_profile.profile_value like '%$keyword%' ";
    } elseif ($facet == 'company') {
        $whereSyntax = " where t_user_profile.profile_key='company' and t_user_profile.profile_value like '%$keyword%' ";
    } elseif ($facet == 'role') {
        $whereSyntax = " where t_role.id like '%$keyword%' or t_role.name like '%$keyword%'";
    } else {
        $whereSyntax = " where t_user.id like '%$keyword%' or t_user.email like '%$keyword%' or t_user.nickname like '%$keyword%' or t_role.id like '%$keyword%' or t_role.name like '%$keyword%'";
    }
    $conn = getDBConnection();
    $result = $conn->query("select count(t_user.serial) from t_user left join t_mapping_user_role on t_mapping_user_role.user_serial = t_user.serial left join t_role on t_role.serial = t_mapping_user_role.role_serial $whereSyntax");
    $set = 0;
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row['count(serial)'];
    }
    $result->free();
    $conn->disconnect();
    return $set;
}
/**
 * user_getAllSearchByFacet
 *
 * 搜索对应用户信息
 *
 * @param object $facet 搜索的列名称
 * @param object $keyword 搜索内容
 * @param object $start 起始位置
 * @param object $size 每页个数
 * @param object $orderBy 排序方法
 *
 * @return array 返回搜索结果
 */
function user_getAllSearchByFacet($facet, $keyword, $start, $size, $orderBy) {
    if (in_array($facet, array('id', 'email', 'nickname'))) {
        $whereSyntax = " where t_user.$facet like '%$keyword%' ";
    } elseif ($facet == 'role') {
        $whereSyntax = " where t_role.id like '%$keyword%' or t_role.name like '%$keyword%'";
    } else {
        $whereSyntax = " where t_user.id like '%$keyword%' or t_user.email like '%$keyword%' or t_user.nickname like '%$keyword%' or t_role.id like '%$keyword%' or t_role.name like '%$keyword%'";
    }
    $conn = getDBConnection();
    $result = $conn->query("select t_user.serial as serial, t_user.id as id, email, nickname, register_time, last_access_time, before_last_access_time, t_role.serial as role_serial, t_role.id as role_id, t_role.name as role_name from t_user left join t_mapping_user_role on t_mapping_user_role.user_serial = t_user.serial left join t_role on t_role.serial = t_mapping_user_role.role_serial $whereSyntax order by t_user.$orderBy");
    $set = array();
    $i = 0;
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        if ($i >= $start) {
            if ($size != - 1 && count($set) >= $size) {
                break;
            }
            $set[] = $row;
        }
        $i++;
    }
    $result->free();
    $conn->disconnect();
    return $set;
}
/**
 * @return string 返回”user“
 */
function role_getDefault() {
    return "user";
}
/**
 * @return array 返回对应数组
 */
function role_getPreserved() {
    return array('admin', 'user', 'guest');
}
/**
 * role_getByField
 *
 * 查询角色信息
 *
 * @param ateing $name 对应列名称
 * @param string $value 对应的名称
 *
 * @return array 返回角色信息
 */
function role_getByField($name, $value) {
    if (!isset($value)) {
        return null;
    } elseif (!is_array($value)) {
        $whereSyntax = "where $name=?";
        $conn = getDBConnection();
        $result = $conn->query("select serial, id, name, description from t_role $whereSyntax", array($value));
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set = $row;
        }
        $result->free();
        $conn->disconnect();
        return $set;
    } elseif (count($value) == 0) {
        return array();
    } else {
        $values = $value;
        $whereSyntax = "where $name in (";
        foreach ($values as $value) {
            $whereSyntax .= "?, ";
        }
        $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
        $whereSyntax .= ")";
        $conn = getDBConnection();
        $result = $conn->query("select serial, id, name, description from t_role $whereSyntax", $values);
        $set = array();
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set[$row[$name]] = $row;
        }
        $result->free();
        $conn->disconnect();
        return $set;
    }
}
/**
 * role_getByUser
 *
 * 查询用户信息
 * @param int $userSerial 用户对应的$serial
 * @return array 返回对应用户信息
 */
function role_getByUser($userSerial) {
    if (!isset($userSerial)) {
        return null;
    } elseif (!is_array($userSerial)) {
        $user = user_getByField("serial", $userSerial);
        if ($user) {
            $conn = getDBConnection();
            $result = $conn->query("select serial, id, name, description from t_role left join t_mapping_user_role on t_mapping_user_role.role_serial = t_role.serial where t_mapping_user_role.user_serial = ?",
                 $user['serial']);
            $set = array();
            while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
                $set = $row;
            }
            $result->free();
            $conn->disconnect();
            return $set;
        } else {
            return null;
        }
    } elseif (count($userSerial) == 0) {
        return array();
    } else {
        $users = user_getByField("serial", $userSerial);
        if (count($users) != 0) {
            $conn = getDBConnection();
            $whereSyntax = " where t_mapping_user_role.user_serial in(";
            $values = array();
            foreach ($users as $user) {
                $whereSyntax .= "?, ";
                $values[] = $user['serial'];
            }
            $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2).")";
            $result = $conn->query("select serial, id, name, description, user_serial from t_role left join t_mapping_user_role on t_mapping_user_role.role_serial = t_role.serial $whereSyntax",
                 $values);
            $set = array();
            while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
                $set[$row['user_serial']] = $row;
            }
            $result->free();
            $conn->disconnect();
            return $set;
        } else {
            return array();
        }
    }
}
/**
 * role_create
 *
 * 创建角色
 *
 * @param array $role 存储角色信息所用的数组
 *
 * @return array 返回最后创建角色的信息
 */
function role_create($role) {
    $conn = getDBConnection();
    $conn->query("insert into t_role(id, name, description) value(?, ?, ?)", array($role['id'], $role['name'],
         $role['description']));
    $result = $conn->query("select last_insert_id()");
    if ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row;
    }
    $result->free();
    $conn->disconnect();
    return $set['last_insert_id()'];
}
/**
 * role_deleteByField
 *
 * 删除角色
 *
 * @param string $name 角色对应的列名称
 * @param int $value 对应的角色$serial
 */
function role_deleteByField($name, $value) {
    $conn = getDBConnection();
    //grant
    $role = role_getByField($name, $value);
    if (!is_array($value)) {
        if ($role) {
            $roles = array($value=>$role);
        } else {
            $roles = array();
        }
    } else {
        $roles = $role;
    }
    if (count($role) != 0) {
        $selectSyntax = "select user_serial from t_mapping_user_role where role_serial in(";
        $selectValue = array();
        foreach ($roles as $role) {
            $selectSyntax .= "?, ";
            $selectValue[] = $role['serial'];
        }
        $selectSyntax = substr($selectSyntax, 0, strlen($selectSyntax) - 2).")";
        $result = $conn->query($selectSyntax, $selectValue);
        $set = array();
        while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $set[] = $row['user_serial'];
        }
        $result->free();
        $defaultRole = role_getByField('id', role_getDefault());
        role_grant($set, $defaultRole['serial']);
    }
    //delete
    if (!isset($value)) {
        return null;
    } elseif (!is_array($value)) {
        $whereSyntax = "where $name=?";
        $conn = getDBConnection();
        $conn->query("delete from t_role $whereSyntax", array($value));
        $conn->disconnect();
    } elseif (count($value) == 0) {
        return array();
    } else {
        $values = $value;
        $whereSyntax = "where $name in (";
        foreach ($values as $value) {
            $whereSyntax .= "?, ";
        }
        $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
        $whereSyntax .= ")";
        $conn = getDBConnection();
        $conn->query("delete from t_role $whereSyntax", $values);
        $conn->disconnect();
    }
}
/**
 * role_update
 *
 * 修改角色信息
 *
 * @param array $role 对应的角色信息
 */
function role_update($role) {
    $conn = getDBConnection();
    $updateValue = array();
    $serial = $role['serial'];
    unset($role['serial']);
    foreach ($role as $field=>$value) {
        $updateFieldSyntax .= "$field=?, ";
        $updateValue[$field] = $value;
    }
    $updateValue['serial'] = $serial;
    $updateFieldSyntax = substr($updateFieldSyntax, 0, strlen($updateFieldSyntax) - 2);
    $conn->query("update t_role set $updateFieldSyntax where serial=?", $updateValue);
    $conn->disconnect();
}

/**
 * role_getCount
 *
 * 查询角色信息条数
 *
 * @return int 返回条数
 */
function role_getCount() {
    $conn = getDBConnection();
    $result = $conn->query("select count(serial) from t_role");
    $set = 0;
    if ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        $set = $row['count(serial)'];
    }
    $result->free();
    $conn->disconnect();
    return $set;
}
/**
 * role_getAll
 *
 * 查询全部角色信息
 *
 * @param object $start 查询起始位置
 * @param object $size 每页条数
 * @param object $orderBy 排序规则
 *
 * @return array 返回角色信息内容
 */
function role_getAll($start, $size, $orderBy) {
    $conn = getDBConnection();
    $result = $conn->query("select serial, id, name, description, count(role_serial) as user_count from t_role left join t_mapping_user_role on t_role.serial = t_mapping_user_role.role_serial group by t_role.serial order by $orderBy");
    $set = array();
    $i = 0;
    while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        if ($i >= $start) {
            if ($size != - 1 && count($set) >= $size) {
                break;
            }
            $set[] = $row;
        }
        $i++;
    }
    $result->free();
    $conn->disconnect();
    return $set;
}
/**
 * role_grant
 *
 * 为用户设置角色
 *
 * @param int $userSerial 对应用户的$serial
 * @param int $roleSerial 对应角色的$serial
 */
function role_grant($userSerial, $roleSerial) {
    $user = user_getByField('serial', $userSerial);
    if (!is_array($userSerial)) {
        if ($user) {
            $users = array($userSerial=>$user);
        } else {
            $users = array();
        }
    } else {
        $users = $user;
    }
    $role = role_getByField('serial', $roleSerial);
    if (count($users) != 0) {
        $conn = getDBConnection();
        //delete
        $deleteSyntax = "delete from t_mapping_user_role where user_serial in (";
        $values = array();
        foreach ($users as $user) {
            $deleteSyntax .= "?, ";
            $values[] = $user['serial'];
        }
        $deleteSyntax = substr($deleteSyntax, 0, strlen($deleteSyntax) - 2).")";
        $conn->query($deleteSyntax, $values);
        if ($role) {
            //insert
            $insertSyntax = "insert into t_mapping_user_role(user_serial, role_serial) values ";
            $values = array();
            foreach ($users as $user) {
                $insertSyntax .= "(?, ?), ";
                $values[] = $user['serial'];
                $values[] = $role['serial'];
            }
            $insertSyntax = substr($insertSyntax, 0, strlen($insertSyntax) - 2);
            $conn->query($insertSyntax, $values);
        }
        $conn->disconnect();
    }
}
/**
 * privilege_update
 *
 * 修改权限信息
 *
 * @param int $roleSerial 对应角色的$serial
 * @param array $privilege 对应权限信息
 */
function privilege_update($roleSerial, $privilege) {
    $role = role_getByField('serial', $roleSerial);
    if (!is_array($roleSerial)) {
        if ($role) {
            $roles = array($roleSerial=>$role);
        } else {
            $roles = array();
        }
    } else {
        $roles = $role;
    }
    $allow = array();
    $deny = array();
    foreach ($privilege['items'] as $key1=>$item1) {
        $on = true;
        foreach ($item1['items'] as $key2=>$item2) {
            if ($item2['allow']) {
                $allow[] = $key1.".".$key2;
            } else {
                $on = false;
                $deny[] = $key1.".".$key2;
            }
        }
        if ($on) {
            $allow[] = $key1;
        } else {
            $deny[] = $key1;
        }
    }
    $default = $privilege['default'];
    foreach ($roles as $role) {
        $conn = getDBConnection();
        $result = $conn->query("select count(role_serial) from t_privilege where role_serial=?", array($role['serial']));
        $count = 0;
        if ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
            $count = $row['count(role_serial)'];
        }
        $result->free();
        if ($count == 0) {
            $conn->query("insert into t_privilege values(?, ?, ?, ?)", array($role['serial'], join(",", $allow),
                 join(",", $deny), $default));
        } else {
            $conn->query("update t_privilege set allow=?, deny=?, `default`=? where role_serial=?", array(join(",",
                 $allow), join(",", $deny), $default, $role['serial']));
        }
        $conn->disconnect();
    }
}
/**
 * privilege_get
 *
 * 获取权限信息
 *
 * @param int $roleSerial 对应角色的$serial
 * @param array $privilege 对应的权限信息
 *
 * @return array 返回权限信息
 */
function privilege_get($roleSerial, $privilege) {
    if (!isset($roleSerial)) {
        return null;
    } elseif (!is_array($roleSerial)) {
        $role = role_getByField('serial', $roleSerial);
        if ($role) {
            $conn = getDBConnection();
            $result = $conn->query("select role_serial, allow, deny, `default` from t_privilege where role_serial=?",
                 $role['serial']);
            while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
                $set = $row;
            }
            $result->free();
            $conn->disconnect();
            if ($set) {
                $allow = explode(",", $set['allow']);
                $deny = explode(",", $set['deny']);
                $default = $set['default'];
            } else {
                $allow = array();
                $deny = array();
                $default = false;
            }
            foreach ($privilege['items'] as $key1=>$item1) {
                $on = true;
                foreach ($item1['items'] as $key2=>$item2) {
                    $key = $key1.".".$key2;
                    if (in_array($key, $allow)) {
                        $privilege['items'][$key1]['items'][$key2]['allow'] = true;
                    } else if (in_array($key, $deny)) {
                        $privilege['items'][$key1]['items'][$key2]['allow'] = false;
                    } else {
                        $privilege['items'][$key1]['items'][$key2]['allow'] = $default;
                    }
                    $on &= $privilege['items'][$key1]['items'][$key2]['allow'];
                }
                $privilege['items'][$key1]['allow'] = $on;
            }
            $privilege['default'] = $default;
            return $privilege;
        } else {
            return null;
        }
    } elseif (count($roleSerial) == 0) {
        return array();
    } else {
        $roles = role_getByField('serial', $roleSerial);
        if (count($roles) != 0) {
            $whereSyntax = "where role_serial in(";
            $values = array();
            foreach ($roles as $role) {
                $whereSyntax .= "?, ";
                $values[] = $role['serial'];
            }
            $whereSyntax = substr($whereSyntax, 0, strlen($whereSyntax) - 2);
            $whereSyntax .= ")";
            $conn = getDBConnection();
            $result = $conn->query("select role_serial, allow, deny, `default` from t_privilege $whereSyntax",
                 $values);
            $set = array();
            while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
                $set[$row['role_serial']] = $row;
            }
            $result->free();
            $conn->disconnect();
        } else {
            $set = array();
        }
        $privilegeArray = array();
        foreach ($set as $roleSerial=>$entry) {
            $allow = explode(",", $entry['allow']);
            $deny = explode(",", $entry['deny']);
            $default = $entry['default'];
            $privilege1 = $privilege;
            foreach ($privilege1['items'] as $key1=>$item1) {
                $key = $key1;
                if (in_array($key, $allow)) {
                    $privilege1['items'][$key1]['allow'] = true;
                } else if (in_array($key, $deny)) {
                    $privilege1['items'][$key1]['allow'] = false;
                } else {
                    $privilege1['items'][$key1]['allow'] = $default;
                }
                foreach ($item1['items'] as $key2=>$item2) {
                    $key = $key1.".".$key2;
                    if (in_array($key, $allow)) {
                        $privilege1['items'][$key1]['items'][$key2]['allow'] = true;
                    } else if (in_array($key, $deny)) {
                        $privilege1['items'][$key1]['items'][$key2]['allow'] = false;
                    } else {
                        $privilege1['items'][$key1]['items'][$key2]['allow'] = $default;
                    }
                }
            }
            $privilege1['default'] = $default;
            $privilegeArray[$roleSerial] = $privilege1;
        }
        return $privilegeArray;
    }
}

function privilege_getById($roleSerial, $id) {
    global $featureManager;
    $featureManager->apply("com.yizin.platform.privilege", $privilege);
    $privilege = privilege_get($roleSerial, $privilege);
    $nodes = explode(".", $id);
    $allow = $privilege;
    foreach ($nodes as $node) {
        $allow = $allow['items'][$node];
    }
    $allow = $allow['allow'];
    return $allow ? "allow" : "deny";
}

function service_site_get_index_session_list($status, $limit = 10) {
	$conn = getDBConnection();
	$where_clause_part;
	if ($status == 'current') {
		$where_clause_part = 'sp.start_time >= DATE_ADD( NOW( ) , INTERVAL -1 DAY ) AND sp.start_time <= DATE_ADD( NOW( ) , INTERVAL 5 DAY ) ';
	} elseif ($status == 'future') {
		$where_clause_part = 'sp.start_time > DATE_ADD( NOW( ) , INTERVAL 5 DAY ) ';
	} elseif ($status == 'past') {
		$where_clause_part = 'sp.start_time < DATE_ADD( NOW( ) , INTERVAL -1 DAY )';
	}
	
	$sql_stmt = "SELECT ss.id_session, sp.start_time, ss.title, p.first_name, p.last_name, DATE_ADD(sp.start_time, INTERVAL sp.duration MINUTE) as end_time
		FROM seminars_profiles sp, seminars_sessions ss, seminars_sessions_speakers sss, people p
		WHERE sp.id_seminar = ss.id_seminar AND ss.id_session = sss.id_session AND sss.id_person = p.id_person
		AND " . $where_clause_part . "
		ORDER BY sp.start_time DESC
		LIMIT ?";

	$result = & $conn->query($sql_stmt, array($limit));
	
	$set = array();
	while ($row = &$result->fetchRow(DB_FETCHMODE_ASSOC)) {
        array_push($set, $row);
    }
    
    $result->free();
	
	
	return $set;
}
?>
